<template>
  <div class="quiz-container">
    <!-- 加载状态 -->
    <div v-if="loading" class="loading-state">
      <el-loading-spinner size="40" />
      <p>加载题目中...</p>
    </div>

    <div v-else-if="questions.length > 0" class="quiz-content">
      <!-- 关闭 -->
      <!-- <el-button 
        @click="handleClose" 
        type="text" 
        class="close-btn"
        aria-label="关闭"
      >
        <el-icon><Close /></el-icon>
      </el-button> -->

      <!-- 题目 -->
      <div class="quiz-actions">
        <el-button 
          @click="downloadCurrentQuestion" 
          type="primary"
          :icon="Download"
          class="download-current-btn"
        >
          下载当前题目
        </el-button>
        <el-button 
          @click="downloadAllQuestions" 
          type="warning"
          :icon="Download"
          class="download-all-btn"
        >
          下载全部题目
        </el-button>
      </div>

      <!-- 题目导航栏 -->
      <div class="question-nav">
        <div 
          v-for="(q, index) in questions" 
          :key="q.id"
          class="nav-item"
          :class="{
            current: currentQuestionIndex === index,
            correct: isSubmitted && userAnswers[index] === q.correctAnswerIndex,
            incorrect: isSubmitted && userAnswers[index] !== null && userAnswers[index] !== q.correctAnswerIndex,
            unanswer: isSubmitted && userAnswers[index] === null,
            completed: !isSubmitted && questionStatus[index],
            uncompleted: !isSubmitted && !questionStatus[index]
          }"
          @click="goToQuestion(index)"
        >
          {{ index + 1 }}
        </div>
      </div>

      <!-- 题目内容 -->
      <div class="question-card">
        <div class="question-header">
          <span class="question-number">第 {{ currentQuestionIndex + 1 }} / {{ questions.length }} 题</span>
          <h3 class="question-content">{{ currentQuestion.question }}</h3>
        </div>

        <div class="options-list">
          <div 
            v-for="(option, index) in currentQuestion.options" 
            :key="index"
            class="option-item"
            :class="{
              selected: !isSubmitted && userAnswers[currentQuestionIndex] === index,
              correct: isSubmitted && index === currentQuestion.correctAnswerIndex,
              incorrect: isSubmitted && userAnswers[currentQuestionIndex] === index && index !== currentQuestion.correctAnswerIndex,
              unselected: isSubmitted && userAnswers[currentQuestionIndex] === null && index !== currentQuestion.correctAnswerIndex
            }"
            :disabled="isSubmitted"
            @click="!isSubmitted && selectOption(index)"
          >
            <span class="option-letter">{{ String.fromCharCode(65 + index) }}</span>
            <span class="option-text">{{ option }}</span>
            <span v-if="isSubmitted" class="option-result">
              <el-icon v-if="index === currentQuestion.correctAnswerIndex" color="green"><Check /></el-icon>
              <el-icon v-else-if="userAnswers[currentQuestionIndex] === index" color="red"><Close /></el-icon>
            </span>
          </div>
        </div>

        <div class="question-actions">
          <el-button 
            @click="prevQuestion" 
            :disabled="currentQuestionIndex === 0"
          >
            上一题
          </el-button>
          <el-button 
            @click="nextQuestion" 
            :disabled="currentQuestionIndex === questions.length - 1"
          >
            下一题
          </el-button>
          <el-button 
            @click="handleSubmit" 
            :disabled="isSubmitted"
            type="primary"
            class="submit-btn"
          >
            提交所有答案
          </el-button>
        </div>

        <div v-if="isSubmitted" class="explanation">
          <h4>答案解析：</h4>
          <p>{{ currentQuestion.explanation || '暂无解析' }}</p>
        </div>
      </div>

      <div v-if="isSubmitted" class="submit-result">
        <h3>答题结果</h3>
        <div class="score-display">
          <span class="score-label">最终得分：</span>
          <span class="score-value">{{ score }} 分</span>
        </div>
        <p>总题数：{{ questions.length }} 题</p>
        <p>做对：<span class="correct-text">{{ correctCount }} 题</span></p>
        <p>做错：<span class="incorrect-text">{{ incorrectCount }} 题</span></p>
        <p>未答：<span class="unanswer-text">{{ unanswerCount }} 题</span></p>
        <el-button @click="resetQuiz" type="success" style="margin-top: 10px;">
          重新开始
        </el-button>
      </div>
    </div>

    <div v-else class="error-state">
      <el-icon color="red" size="40"><Loading /></el-icon>
      <p>题目加载中.....</p>
      <el-button @click="loadQuestions" type="primary" style="margin-top: 10px;">
        重试
      </el-button>
    </div>

    <el-dialog
      v-model="showUncompletedDialog"
      title="提示"
      width="30%"
    >
      <p>您还有 {{ uncompletedCount }} 题未完成，确定要提交吗？</p>
      <template #footer>
        <el-button @click="showUncompletedDialog = false">取消</el-button>
        <el-button type="primary" @click="confirmSubmit">确定提交</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
// 修正导入路径，确保与Element Plus版本兼容
import { ref, onMounted, computed, defineProps, watch, defineEmits } from 'vue';
import { Check, Close, Loading, Document, Download } from '@element-plus/icons-vue';
import { ElButton, ElIcon, ElMessage, ElDialog, ElLoading } from 'element-plus';

const ElLoadingSpinner = ElLoading.Component;

// 定义组件属性和事件
const props = defineProps<{
  questions: {
    id: string;
    question: string;
    options: string[];
    correctAnswerIndex: number;
    explanation?: string;
  }[];
  loading: boolean;
  visible: boolean;
}>();

const emit = defineEmits<{
  (e: 'close'): void;
}>();

// 状态管理
const currentQuestionIndex = ref(0);
const userAnswers = ref<(number | null)[]>([]);
const questionStatus = ref<boolean[]>([]);
const isSubmitted = ref(false);
const showUncompletedDialog = ref(false);
const savedQuestions = ref<typeof props.questions[0][]>([]);
const allSavedQuestions = ref<typeof props.questions[0][]>([]);

// 清除所有答题状态
const clearQuizState = () => {
  userAnswers.value = [];
  questionStatus.value = [];
  currentQuestionIndex.value = 0;
  isSubmitted.value = false;
  showUncompletedDialog.value = false;
  localStorage.removeItem('quizState');
};

// 关闭当前测验
const handleClose = () => {
  clearQuizState();
  emit('close');
};

// 监听题目变化：新题加载时自动重置状态
watch(
  () => props.questions,
  (newQuestions) => {
    if (newQuestions && newQuestions.length > 0) {
      clearQuizState();
      loadQuestions();
    }
  },
  { deep: true }
);

// 监听显示状态变化
watch(
  () => props.visible,
  (newVisible) => {
    if (!newVisible) {
      clearQuizState();
    }
  }
);

// 当前题目
const currentQuestion = computed(() => {
  return props.questions[currentQuestionIndex.value];
});

// 未完成题目数量
const uncompletedCount = computed(() => {
  return questionStatus.value.filter(status => !status).length;
});

// 答题结果统计
const correctCount = computed(() => {
  if (!isSubmitted.value) return 0;
  return props.questions.filter((q, index) => {
    return userAnswers.value[index] === q.correctAnswerIndex;
  }).length;
});

const incorrectCount = computed(() => {
  if (!isSubmitted.value) return 0;
  return props.questions.filter((q, index) => {
    return userAnswers.value[index] !== null && userAnswers.value[index] !== q.correctAnswerIndex;
  }).length;
});

const unanswerCount = computed(() => {
  if (!isSubmitted.value) return 0;
  return props.questions.filter((_, index) => {
    return userAnswers.value[index] === null;
  }).length;
});

const score = computed(() => {
  if (!isSubmitted.value || props.questions.length === 0) return 0;
  const perQuestionScore = 100 / props.questions.length;
  return Math.round(correctCount.value * perQuestionScore);
});

// 下载功能
const downloadCurrentQuestion = () => {
  const question = currentQuestion.value;
  if (!question) return;

  const mdContent = `# 题目：${question.question}
  
## 选项：
${question.options.map((opt, idx) => {
  const letter = String.fromCharCode(65 + idx);
  const isCorrect = idx === question.correctAnswerIndex;
  return `${letter}. ${opt} ${isCorrect ? "（正确答案）" : ""}`;
}).join("\n")}

## 解析：
${question.explanation || "无解析"}
`;

  const fileName = `题目_${question.id}.md`;
  downloadFile(mdContent, fileName, "text/markdown");
};

const downloadAllQuestions = () => {
  if (props.questions.length === 0) {
    ElMessage.warning("没有可下载的题目");
    return;
  }

  let mdContent = `# 题目合集（共${props.questions.length}题）\n\n`;
  
  props.questions.forEach((q, index) => {
    mdContent += `## 第${index + 1}题：${q.question}\n`;
    mdContent += "### 选项：\n";
    q.options.forEach((opt, idx) => {
      const letter = String.fromCharCode(65 + idx);
      const isCorrect = idx === q.correctAnswerIndex;
      mdContent += `${letter}. ${opt} ${isCorrect ? "（正确答案）" : ""}\n`;
    });
    mdContent += `### 解析：\n${q.explanation || "无解析"}\n\n`;
  });

  const date = new Date().toLocaleDateString().replace(/\//g, "-");
  const fileName = `题目合集_${date}.md`;
  downloadFile(mdContent, fileName, "text/markdown");
};

const downloadFile = (content: string, fileName: string, mimeType: string) => {
  try {
    const blob = new Blob([content], { type: mimeType });
    const url = URL.createObjectURL(blob);
    const a = document.createElement("a");
    a.href = url;
    a.download = fileName;
    document.body.appendChild(a);
    a.click();
    document.body.removeChild(a);
    URL.revokeObjectURL(url);
    ElMessage.success(`已开始下载：${fileName}`);
  } catch (error) {
    ElMessage.error("下载失败，请重试");
    console.error("下载错误：", error);
  }
};

// 加载保存的题目
const loadSavedQuestions = () => {
  try {
    let singleSaved = localStorage.getItem('savedQuestions');
    let allSaved = localStorage.getItem('allSavedQuestions');
    
    if (singleSaved) savedQuestions.value = JSON.parse(singleSaved);
    if (allSaved) allSavedQuestions.value = JSON.parse(allSaved);
  
  } catch (error) {
    console.error("加载保存的题目失败：", error);
  }
};

// 加载题目（初始化状态）
const loadQuestions = async () => {
  try {
    userAnswers.value = new Array(props.questions.length).fill(null);
    questionStatus.value = new Array(props.questions.length).fill(false);
    currentQuestionIndex.value = 0;
    isSubmitted.value = false;
    loadSavedQuestions();
  } catch (error) {
    console.error('加载题目失败:', error);
  }
};

// 重置测验
const resetQuiz = () => {
  clearQuizState();
  loadQuestions();
};

// 题目导航
const goToQuestion = (index: number) => {
  currentQuestionIndex.value = index;
};

const prevQuestion = () => {
  if (currentQuestionIndex.value > 0) {
    currentQuestionIndex.value--;
  }
};

const nextQuestion = () => {
  if (currentQuestionIndex.value < props.questions.length - 1) {
    currentQuestionIndex.value++;
  }
};

// 选择选项
const selectOption = (index: number) => {
  if (!isSubmitted.value) {
    userAnswers.value[currentQuestionIndex.value] = index;
    questionStatus.value[currentQuestionIndex.value] = true;
    userAnswers.value = [...userAnswers.value];
    questionStatus.value = [...questionStatus.value];
  }
};

// 提交答案
const handleSubmit = () => {
  if (uncompletedCount.value > 0) {
    showUncompletedDialog.value = true;
  } else {
    confirmSubmit();
  }
};

const confirmSubmit = () => {
  showUncompletedDialog.value = false;
  isSubmitted.value = true;
};

// 初始化
onMounted(() => {
  if (props.questions.length > 0) {
    loadQuestions();
  }
});
</script>

<style scoped lang="less">
.quiz-container {
  max-width: 800px;
  margin: 20px auto;
  padding: 0 20px;
  position: relative;
}

.quiz-content {
  margin-top: 20px;
}

.quiz-actions {
  margin-bottom: 15px;
  padding: 10px 0;
  border-bottom: 1px solid #f0f0f0;
  display: flex;
  gap: 10px;
}

.question-nav {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  margin-bottom: 20px;
  padding: 15px;
  background: #f9f9f9;
  border-radius: 8px;
}

.nav-item {
  width: 30px;
  height: 30px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  font-weight: bold;
  transition: all 0.2s;
}

.nav-item.completed {
  background: #52c41a;
  color: white;
}
.nav-item.uncompleted {
  background: #ffb800;
  color: #fff;
}

.nav-item.correct {
  background: #52c41a;
  color: white;
}
.nav-item.incorrect {
  background: #ff4d4f;
  color: white;
}
.nav-item.unanswer {
  background: #d9d9d9;
  color: white;
}

.nav-item.current {
  transform: scale(1.15);
  z-index: 10;
  box-shadow: 0 0 0 2px rgba(24, 144, 255, 0.3);
}

.question-card {
  background: #fff;
  border-radius: 12px;
  box-shadow: 0 2px 15px rgba(0, 0, 0, 0.05);
  padding: 25px;
  margin-bottom: 20px;
}

.question-header {
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 1px solid #f0f0f0;
  
  .question-number {
    display: inline-block;
    background: #f0f5ff;
    color: #1890ff;
    padding: 3px 10px;
    border-radius: 12px;
    font-size: 14px;
    margin-bottom: 10px;
  }
  
  .question-content {
    margin: 0;
    font-size: 18px;
    color: #333;
  }
}

.options-list {
  margin-bottom: 25px;
}

.option-item {
  display: flex;
  align-items: center;
  padding: 12px 15px;
  border: 1px solid #e8e8e8;
  border-radius: 8px;
  margin-bottom: 10px;
  transition: all 0.2s;
  cursor: pointer;
}

.option-item:hover {
  background-color: #f5f5f5;
}

.option-item.selected {
  border-color: #1890ff;
  background-color: #e6f7ff;
}

.option-item.correct {
  border-color: #52c41a;
  background-color: #f6ffed;
}
.option-item.incorrect {
  border-color: #ff4d4f;
  background-color: #fff2f0;
}
.option-item.unselected {
  border-color: #e8e8e8;
  background-color: #fafafa;
}

.option-letter {
  width: 24px;
  height: 24px;
  border-radius: 50%;
  display: inline-flex;
  align-items: center;
  justify-content: center;
  background: #f0f0f0;
  margin-right: 12px;
  font-weight: bold;
}

.option-item.correct .option-letter {
  background: #52c41a;
  color: white;
}
.option-item.incorrect .option-letter {
  background: #ff4d4f;
  color: white;
}

.option-result {
  margin-left: auto;
}

.question-actions {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
}

.submit-btn {
  margin-left: auto;
}

.explanation {
  padding: 15px;
  background-color: #f9f9f9;
  border-radius: 8px;
  border-left: 4px solid #1890ff;
  margin-top: 20px;
  
  h4 {
    margin: 0 0 10px 0;
    color: #1890ff;
    font-size: 16px;
  }
  
  p {
    margin: 0;
    color: #555;
    line-height: 1.6;
  }
}

.submit-result {
  background: #fff;
  border-radius: 12px;
  box-shadow: 0 2px 15px rgba(0, 0, 0, 0.05);
  padding: 25px;
  text-align: center;
  
  .correct-text {
    color: #52c41a;
    font-weight: bold;
  }
  .incorrect-text {
    color: #ff4d4f;
    font-weight: bold;
  }
  .unanswer-text {
    color: #8c8c8c;
    font-weight: bold;
  }
}

.score-display {
  margin: 20px 0;
  padding: 15px;
  background: #f0f5ff;
  border-radius: 8px;
  display: inline-flex;
  align-items: center;
  
  .score-value {
    font-size: 24px;
    font-weight: bold;
    color: #1890ff;
  }
}

.loading-state, .error-state {
  text-align: center;
  padding: 50px 20px;
  background: #fff;
  border-radius: 12px;
  box-shadow: 0 2px 15px rgba(0, 0, 0, 0.05);
}

.download-current-btn, .download-all-btn {
  flex: 1;
  max-width: 150px;
  margin-left: 10px;
}

// 关闭按钮样式
.close-btn {
  position: absolute;
  top: 15px;
  right: 15px;
  z-index: 100;
  color: #606266;
  padding: 4px;
  
  &:hover {
    color: #ff4d4f;
    background-color: #f5f5f5;
    border-radius: 50%;
  }
}

// 适配小屏幕
@media (max-width: 768px) {
  .quiz-actions {
    flex-wrap: wrap;
  }
  .download-current-btn, .download-all-btn {
    max-width: 100%;
    width: 48%;
    margin-left: 0;
    margin-bottom: 8px;
  }
}
</style>